<script setup lang="ts">
import type { TreeNodeData } from 'element-plus'
import { ElMessage } from 'element-plus'
import { JSONPath } from 'jsonpath-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import eventBus from '~/composables/eventBus'
import jsonToTree from '~/composables/treetool'
import { useJsonStore } from '~/stores/json'

const router = useRouter()
// 新增导入
definePageMeta({
  layout: 'default',
  keepalive: true,
})
const upload_dialog_visible = ref(false)
// 定义所有事件处理函数
function handleUpload() {
  upload_dialog_visible.value = true
}

const jsonStore = useJsonStore() // 新增store实例
const jsonPath = ref('$') // 新增jsonPath变量
// 移除原有的textarea ref定义
const treeRef = ref()
const selectedNode = ref()
const flatList = ref<any[]>([])
const cols = ref<any[]>([])
function handleConvert() {
  // ElMessage.info('转换功能已触发')
  // 这里添加转换逻辑
  try {
    const content = JSON.parse(jsonStore.source)
    jsonStore.setContent(content)
  }
  catch (error) {
    // console.error('解析JSON失败:', error)
    ElMessage.error({
      showClose: true,
      message: `Json内容解析失败: ${error instanceof Error ? error.message : String(error)}`,
    })
    return
  }
  ElMessage.success({
    showClose: true,
    duration: 500,
    message: 'Json解析完成.',
  })
}

// interface TreeNode {
//   label: string
//   children?: TreeNode[]
// }

interface TreeNode {
  label?: string // 节点显示名称
  children: TreeNode[] // 子节点（始终为数组）
  value?: any // 可选：原始值（非对象类型时存储）
}

const jsonTree = ref<TreeNode[]>([])

function handleRefreshNodes() {
  // ElMessage.info('刷新节点功能已触发')
  // 这里添加刷新节点逻辑
  // 把jsonStore的内容转化为el-tree需要的数据结构
  const tree = jsonToTree(jsonStore.content).children
  jsonTree.value = tree
  // 重置选中节点
  treeRef.value?.setCheckedKeys([])
  jsonPath.value = '$'
  RefreshTable()
  selectedNode.value = null
  ElMessage.success({
    showClose: true,
    duration: 1000,
    message: '数据刷新完成.',
  })
}

function handleRefreshTables() {
  ElMessage.info('刷新表格功能已触发')
  // 这里添加刷新表格逻辑
  const nodes = treeRef.value.getCheckedNodes()
  if (nodes.length === 0) {
    showJsonInTable(jsonStore.content)
  }
  else {
    const path = nodes[0].path
    const json = JSONPath({ path, json: jsonStore.content })
    showJsonInTable(json) // 刷新表格
  }
}

function handleRefreshAll() {
  // ElMessage.info('刷新全部功能已触发')
  // 这里添加刷新全部逻辑，跳转到about
}

function handleExportCSV() {
  // ElMessage.info('导出CSV功能已触发')
  // 这里添加导出CSV逻辑
  const path = jsonPath.value.length > 0 ? jsonPath.value : '$.*'
  const json = JSONPath({ path, json: jsonStore.content })
  toCSV(json)
}

function handleExportXLS() {
  // ElMessage.info('导出XLS功能已触发')
  // 这里添加导出XLS逻辑
  const path = jsonPath.value
  const json = JSONPath({ path, json: jsonStore.content })
  toXLS(json)
}

function handleExportXLSX() {
  // ElMessage.info('导出XLSX功能已触发')
  // 这里添加导出XLSX逻辑
  const path = jsonPath.value
  const json = JSONPath({ path, json: jsonStore.content })
  toXLSX(json)
}

function handleAbout() {
  // ElMessage.info('关于页面功能已触发')
  // 这里添加关于页面逻辑
  router.push('/about')
}

onMounted(() => {
  // 注册所有事件监听
  eventBus.on('upload-click', handleUpload)
  eventBus.on('convert-click', handleConvert)
  eventBus.on('refresh-nodes-click', handleRefreshNodes)
  eventBus.on('refresh-tables-click', handleRefreshTables)
  eventBus.on('refresh-all-click', handleRefreshAll)
  eventBus.on('export-csv-click', handleExportCSV)
  eventBus.on('export-xls-click', handleExportXLS)
  eventBus.on('export-xlsx-click', handleExportXLSX)
  eventBus.on('about-click', handleAbout)
})

onUnmounted(() => {
  // 组件卸载时移除所有监听器
  eventBus.off('upload-click', handleUpload)
  eventBus.off('convert-click', handleConvert)
  eventBus.off('refresh-nodes-click', handleRefreshNodes)
  eventBus.off('refresh-tables-click', handleRefreshTables)
  eventBus.off('refresh-all-click', handleRefreshAll)
  eventBus.off('export-csv-click', handleExportCSV)
  eventBus.off('export-xls-click', handleExportXLS)
  eventBus.off('export-xlsx-click', handleExportXLSX)
  eventBus.off('about-click', handleAbout)
})

const props = {
  value: 'id',
  label: 'label',
  children: 'children',
}
function RefreshTable(path = '') {
  // console.warn('refresh table', path)
  if (path === '') {
    showJsonInTable(jsonStore.content)
    return
  }
  const json = JSONPath({ path, json: jsonStore.content })
  showJsonInTable(json) // 刷新表格
}
function handleSingleCheck(currentNode: TreeNodeData) {
  // 单选逻辑，反选
  // const checkedKeys = treeRef.value?.getCheckedKeys()
  if (selectedNode.value === currentNode.id) {
    treeRef.value?.setCheckedKeys([])
    jsonPath.value = '$'
    RefreshTable()
    selectedNode.value = null
    return
  }

  treeRef.value?.setCheckedKeys([currentNode.id]) // 单选逻辑
  selectedNode.value = currentNode.id
  jsonPath.value = currentNode.path
  RefreshTable(jsonPath.value)
}
function handleGo() {
  RefreshTable(jsonPath.value)
}
function handleHelp() {
  ElMessageBox.alert(
    '使用<a href="https://www.npmjs.com/package/jsonpath-plus/" target="_blank">jsonpath-plus</a>查询Json内的内容',
    'JsonPath',
    {
      dangerouslyUseHTMLString: true,
    },
  )
}

function showJsonInTable(json: any) {
  flatList.value = Array.isArray(json) ? json : [json]
  cols.value = genColumns(flatList.value[0] as any) as unknown as any[]
}
</script>

<template>
  <div class="h-[98%]">
    <upload-dialog :visible="upload_dialog_visible" @update:visible="upload_dialog_visible = $event" />
    <div class="h-full flex flex-col">
      <div class="m-2 mb-0 pb-1 pt-1">
        <el-input
          v-model="jsonStore.source" :rows="3" type="textarea"
          placeholder="Please input the content of the JSON object."
        />
      </div>
      <div class="w-full flex flex-1 flex-row" style="min-height: 0;">
        <div class="uni-container m-2 w-80 p2">
          <el-auto-resizer>
            <template #default="{ height, width }">
              <el-tree-v2
                ref="treeRef" class="h-full w-full" show-checkbox :data="jsonTree" :props="props"
                :width="width" :height="height" :check-strictly="true" node-key="id" highlight-current
                @check="handleSingleCheck"
              />
            </template>
          </el-auto-resizer>
        </div>
        <div class="bg-gray-100a uni-container m-2 ml-0 flex-1 pb-2 pr-2 pt-2">
          <el-auto-resizer>
            <template #default="{ height, width }">
              <el-table-v2
                :columns="cols" :data="flatList" :width="width" :height="height" check-on-click-leaf="false"
                check-strictly fixed
              />
            </template>
          </el-auto-resizer>
        </div>
      </div>
      <div class="ml-2 mr-2 w-full">
        <el-input v-model="jsonPath" style="max-width: 98%" placeholder="Please input" width="80%">
          <template #prepend>
            JsonPath
          </template>
          <template #append>
            <el-button-group>
              <el-button @click="handleGo">
                Go
              </el-button>
              <el-button @click="handleHelp">
                ?
              </el-button>
            </el-button-group>
          </template>
        </el-input>
      </div>
    </div>
  </div>
</template>

<style lang="css" scoped>
.uni-container {
  border: 1px solid #eee;
}
</style>
